/**
 * Yolema.com Inc.
 * Copyright (c) 2011-2012 All Rights Reserved.
 */
package org.grayrabbit.pay.chinapnr;

import org.grayrabbit.pay.chinapnr.common.PnrConstants;
import org.grayrabbit.pay.chinapnr.config.ChinapnrInfo;
import org.grayrabbit.pay.core.model.exception.PayException;
import org.grayrabbit.pay.utils.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import chinapnr.SecureLink;

/**
 * 汇付
 * 
 * @author wy
 * @version $Id: Chinapnr.java, v 0.1 2012-10-1 上午10:15:13 wy Exp $
 */
public class Chinapnr {

    private final static Logger LOG = LoggerFactory.getLogger(Chinapnr.class);

    /**
     * 获取签名的数据
     * <li>MerData = Version + MerId + OrdId + TransAmt + TransType + GateId + MerPriv + RetUrl 
     * 
     * @param merId
     * @param merData
     * @return
     */
    public static String getSignValue(String merId, String merData) {

        SecureLink sl = new SecureLink();

        String path = FileUtil.getClassPath() + ChinapnrInfo.MERPR_KEY;
        LOG.info("私钥路径:{}", path);
        //签名
        int ret = sl.SignMsg(merId, path, merData);
        if (ret != 0) {
            throw new PayException(PnrConstants.RETURN_RESULT_MAP.get(ret));
        }
        return sl.getChkValue();
    }

    /**
     * 验证返回签名的数据
     * 
     * <li>merData = CmdId + MerId + RespCode + TrxId + OrdAmt + CurCode + Pid + OrdId + MerPriv + RetType + DivDetails + GateId
     * 
     * @param merData
     * @param chkValue
     * @return
     */
    public static boolean veriSignMsg(String merData, String chkValue) {

        //签名
        SecureLink sl = new SecureLink();

        String path = FileUtil.getClassPath() + ChinapnrInfo.PGPUBK_KEY;

        int ret = sl.VeriSignMsg(path, merData, chkValue);
        if (ret != 0) {
            LOG.info("验证返回交易失败" + PnrConstants.RETURN_RESULT_MAP.get(ret));
            return false;
        }
        return true;
    }

    /**
     * 加密数据
     *CardNo + "|" + ValidDate + "|" + Cvv2 + "|" + IdType + "|" + IdNo + "|" + Name
     * 
     * @param merData
     * @param chkValue
     * @return
     */
    public static String encData(String merData) {

        //签名
        SecureLink sl = new SecureLink();

        String path = FileUtil.getClassPath() + ChinapnrInfo.PGPUBK_KEY;

        int ret = sl.EncOrderMsg(path, merData);
        if (ret != 0) {
            LOG.info("加密数据失败" + PnrConstants.RETURN_RESULT_MAP.get(ret));
            throw new PayException(PnrConstants.RETURN_RESULT_MAP.get(ret));
        }
        return sl.getEncMsg();
    }

}
